package com.hw.utils;

import java.net.InetAddress;

import javax.servlet.http.HttpServletRequest;

public class IpUtil {
	/**
	 * 验证本地IP是否在指定范围内
	 * @param args
	 */
	public static void main(String[] args){
		String ipks="0.0.0.0";
		//String ipks="192.168.1.1";
		//String ipjs="0.0.0.0";
		String ipjs="192.168.1.2";
		boolean f=ipIsValid(ipks,ipjs);
		System.out.println(f);
	}
	/*
	 * 判断本地IP地址是否在范围内
	 */
	public static boolean ipIsValid(String ipks,String ipjs){
		String local_IP = null;
		String regex = "((25[0-5]|2[0-4]\\d|1\\d{2}|[1-9]\\d|\\d)\\.){3}(25[0-5]|2[0-4]\\d|1\\d{2}|[1-9]\\d|\\d)";   
		if ((!ipks.matches(regex))&&(ipjs.matches(regex)))
			return false;
		local_IP = getIp();
		if(ipjs.equals("0.0.0.0"))
			ipjs="255.255.255.255";
        long ips = 0L, ipe = 0L, ipl = 0L;   
        ips=getIpSp(ipks);
        ipe=getIpSp(ipjs);
        ipl=getIpSp(local_IP);
        return ipl>=ips&&ipl<=ipe;
	}
	/*
	 * 把IP转化为long型
	 */
	public static long getIpSp(String ip){
		String[] ipsp=null;
		long ipl=0L;
		if(!ip.equals("0.0.0.0")){
			ipsp= ip.split("\\.");
			for (int i = 0; i < 4; ++i) {   
				ipl = ipl << 8 | Integer.parseInt(ipsp[i]);   
	        }  
		}
		return ipl;
	}
	/*
	 * 获取本地IP
	 */
	public static String getIp(){
		String IP = null;
		try{ 
	        InetAddress address = InetAddress.getLocalHost(); 
	        IP = address.getHostAddress();
	        //System.out.println(IP);
	    }catch(Exception e){ 
	        e.printStackTrace(); 
	    }
		return IP;
	}
	public static String getIpAddr(HttpServletRequest request) throws Exception{
		String ip = request.getHeader("X-Real-IP");
		if (!StringUtils.isBlank(ip) && !"unknown".equalsIgnoreCase(ip)) {
		return ip;
		}
		ip = request.getHeader("X-Forwarded-For");
		if (!StringUtils.isBlank(ip) && !"unknown".equalsIgnoreCase(ip)) {
		// 多次反向代理后会有多个IP值，第一个为真实IP。
		int index = ip.indexOf(',');
		if (index != -1) {
		return ip.substring(0, index);
		} else {
		return ip;
		}
		} else {
		return request.getRemoteAddr();
		}
		}

}
